import React, {Component, PropTypes} from 'react'
import styles from './index.css';

import {connect} from 'dva';
import DateBetween from './dateBetween'
import moment from 'moment'

/**
 * Count down module
 * A simple count down component.
 **/
class Countdown extends Component {

	constructor(props) {
		super(props)
		var diff = new moment(props.options.endDate,'x').diff(new moment(props.options.startDate,'x'))

		this.state = {
			diff,
			remaining: null,
		}
	}

	componentDidMount() {
		this.tick()
		this.interval = setInterval(this.tick.bind(this), 1000)
	}

	componentWillUnmount() {
		clearInterval(this.interval)
	}

	formatNumber(number) {
		return number < 10 ? '0' + number : number;
	}

	formatTime(days,hours, mins, secs) {
		return `${this.formatNumber(days)}:${this.formatNumber(hours)}:${this.formatNumber(mins)}:${this.formatNumber(secs)}`
	}

	tick() {
		if(this.state.expired) return ;

		const diff = this.state.diff - 1000 ;
		const duration = moment.duration(diff)

		if (diff < 0) { //到达倒数时间
			window.clearInterval(this.interval)
			this.setState({
				expired:true,
				remaining: "00:00:00"
			})
			this.props.onExpired()
			this.props.options['onExpired'] ? this.props.options.onExpired() : false
		} else  { //剩余时间在一天内才进行倒数
			let remaining = this.formatTime(duration.days(),duration.hours(), duration.minutes(), duration.seconds())
			this.setState({
				diff,
				remaining
			})
		}
	}

	render() {
		return (
				<div className={styles.reactCountDown} style={{display: this.state.expired ? 'none' : 'block'}}>
					<span className={styles.prefix}> {this.props.options.prefix}</span>
					<span className={styles.data}> {this.state.remaining}</span>
				</div>
		)
	};
}

export default connect(state => {
	return {
	}
})(Countdown);
